package org.eclipsercp.hyperbola.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipsercp.hyperbola.Application;
import org.eclipsercp.hyperbola.common.UIConstants;
import org.eclipsercp.hyperbola.editors.ChatEditor;
import org.eclipsercp.hyperbola.editors.ChatEditorInput;
import org.eclipsercp.hyperbola.model.ContactEntry;

public class ChatAction extends Action implements ISelectionListener,
		IWorkbenchAction {

	public static final String ACTION_ID = ChatAction.class.getName();
	private final IWorkbenchWindow window;
	private IStructuredSelection selection;

	public ChatAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ACTION_ID);
		setText("&Chat");
		setToolTipText("Chat with the selected contact.");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(
				Application.PLUGIN_ID, UIConstants.Image.GROUP));
		window.getSelectionService().addSelectionListener(this);
	}

	@Override
	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}

	@Override
	public void run() {
		ContactEntry entry = (ContactEntry) selection.getFirstElement();
		IWorkbenchPage activePage = window.getActivePage();
		ChatEditorInput input = new ChatEditorInput(entry.getName());
		try {
			activePage.openEditor(input, ChatEditor.ID);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
		if (incoming instanceof IStructuredSelection) {
			selection = (IStructuredSelection) incoming;
			setEnabled(selection.size() == 1
					&& selection.getFirstElement() instanceof ContactEntry);
		} else {
			setEnabled(false);
		}
	}
}
